<template>
  <div class="meeting-assistant">
    <el-container>
      <!-- 顶部导航栏 -->
      <el-header>
        <div class="header-content">
          <el-avatar shape="circle" icon="el-icon-user" class="avatar"></el-avatar>
          <h1>本地会议助手</h1>
          <el-button type="primary" @click="createNewMeeting">新建会议</el-button>
        </div>
      </el-header>

      <!-- 主要内容区域 -->
      <el-main>
        <el-tabs v-model="activeTab" type="border-card">
          <!-- 会议列表标签页 -->
          <el-tab-pane label="会议列表" name="meetingList">
            <el-input
              placeholder="搜索会议..."
              prefix-icon="el-icon-search"
              v-model="searchQuery"
              class="search-input"
            ></el-input>

            <el-table :data="meetings" style="width: 100%">
              <el-table-column prop="id" label="会议ID" width="80"></el-table-column>
              <el-table-column prop="title" label="会议标题"></el-table-column>
              <el-table-column prop="date" label="会议日期" width="180"></el-table-column>
              <el-table-column prop="status" label="状态" width="100">
                <template v-slot:default="scope">
                  <el-tag :type="scope.row.status === '进行中' ? 'success' : 'info'">
                    {{ scope.row.status }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="150">
                <template v-slot:default="scope">
                  <el-button
                    size="small"
                    @click="viewMeetingDetail(scope.row.id)"
                  >
                    查看
                  </el-button>
                  <el-button
                    size="small"
                    type="primary"
                    @click="startMeeting(scope.row.id)"
                    v-if="scope.row.status === '未开始'"
                  >
                    开始
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>

          <!-- 正在进行的会议标签页 -->
          <el-tab-pane label="进行中会议" name="ongoingMeeting">
            <div v-if="currentMeeting" class="ongoing-meeting">
              <h2>{{ currentMeeting.title }}</h2>
              <p class="meeting-time">开始时间: {{ currentMeeting.startTime }}</p>

              <!-- 隐藏的文件输入元素 -->
              <input 
                type="file" 
                ref="fileInput"
                style="display: none;"
                @change="handleFileSelect"
                accept=".wav,.mp3,.m4a,.flac,.ogg,.aac,.wma,.mp4,.avi,.mov,.mkv,.webm"
              />

              <div class="meeting-controls">
                <el-button type="primary" @click="startRecording">开始录音</el-button>
                <el-button type="danger" @click="stopRecording" v-if="isRecording">停止录音</el-button>
                <el-button :loading="isUploading" @click="uploadAudio">上传音频</el-button>
              </div>
              <p v-if="selectedFile" class="selected-file">已选择文件: {{ selectedFile.name }}</p>
              <p v-if="uploadProgress > 0" class="upload-progress">上传进度: {{ uploadProgress }}%</p>

              <div class="recording-status" v-if="isRecording">
                <el-icon class="recording-icon"><microphone /></el-icon>
                <span>正在录音...</span>
              </div>

              <el-divider>会议实时转写</el-divider>
              <div class="transcription">
                <p v-for="(item, index) in transcription" :key="index">
                  <span class="speaker">{{ item.speaker }}:</span> {{ item.content }}
                </p>
                <div v-if="transcription.length === 0" class="empty-transcription">
                  <el-empty description="暂无转写内容" />
                </div>
              </div>
            </div>
            <div v-else class="no-meeting">
              <el-empty description="当前没有进行中的会议"></el-empty>
              <el-button type="primary" style="margin-top: 20px" @click="createNewMeeting">新建会议</el-button>
            </div>
          </el-tab-pane>

          <!-- 会议记录标签页 -->
          <el-tab-pane label="会议记录" name="meetingRecords">
            <el-table :data="meetingRecords" style="width: 100%">
              <el-table-column prop="id" label="记录ID" width="80"></el-table-column>
              <el-table-column prop="meetingTitle" label="会议标题"></el-table-column>
              <el-table-column prop="date" label="会议日期" width="180"></el-table-column>
              <el-table-column prop="summary" label="会议总结" :show-overflow-tooltip="true"></el-table-column>
              <el-table-column label="操作" width="150">
                <template v-slot:default="scope">
                  <el-button size="small" @click="viewRecordDetail(scope.row.id)">查看详情</el-button>
                  <el-button size="small" type="success" @click="generateSummary(scope.row.id)">生成总结</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-tab-pane>
        </el-tabs>
      </el-main>
    </el-container>

    <!-- 新建会议对话框 -->
    <el-dialog title="新建会议" :visible.sync="dialogVisible" width="500px">
      <el-form ref="meetingForm" :model="meetingForm" label-width="80px">
        <el-form-item label="会议标题" prop="title">
          <el-input v-model="meetingForm.title"></el-input>
        </el-form-item>
        <el-form-item label="会议日期" prop="date">
          <el-date-picker v-model="meetingForm.date" type="date" placeholder="选择日期"></el-date-picker>
        </el-form-item>
        <el-form-item label="会议参与者">
          <el-select v-model="meetingForm.participants" multiple placeholder="选择参与者">
            <el-option v-for="user in users" :key="user.id" :label="user.name" :value="user.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="会议备注">
          <el-input v-model="meetingForm.notes" type="textarea" placeholder="请输入会议备注"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveMeeting">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted, nextTick } from 'vue';
import { ElMessage } from 'element-plus';

export default {
  name: 'MeetingAssistant',
  components: {},
  setup() {
    // 响应式数据
    const activeTab = ref('meetingList');
    const searchQuery = ref('');
    const meetings = ref([
      { id: 1, title: '产品需求会议', date: '2023-08-17', status: '未开始' },
      { id: 2, title: '技术架构讨论', date: '2023-08-16', status: '已结束' },
      { id: 3, title: '周例会', date: '2023-08-15', status: '已结束' },
    ]);
    const currentMeeting = ref(null);
    const isRecording = ref(false);
    const transcription = ref([
      // { speaker: '主持人', content: '大家好，欢迎参加今天的会议。' },
      // { speaker: '成员A', content: '很高兴参加这次会议。' },
    ]);
    const meetingRecords = ref([
      { id: 1, meetingTitle: '技术架构讨论', date: '2023-08-16', summary: '讨论了新项目的技术架构选型，决定使用Vue3和FastAPI。' },
      { id: 2, meetingTitle: '周例会', date: '2023-08-15', summary: '回顾了上周工作进展，安排了本周工作任务。' },
    ]);
    const dialogVisible = ref(false);
    const meetingForm = reactive({
      title: '',
      date: '',
      participants: [],
      notes: '',
    });
    const users = ref([
      { id: 1, name: '张三' },
      { id: 2, name: '李四' },
      { id: 3, name: '王五' },
    ]);
    const selectedFile = ref(null);
    const isUploading = ref(false);
    const uploadProgress = ref(0);
    const pollTimer = ref(null);

    // 生命周期钩子
    onMounted(() => {
      // 初始化数据
    });

    // 文件验证函数
    const validateFile = (file) => {
      // 支持的文件类型
      const validTypes = [
        'audio/wav', 'audio/mp3', 'audio/m4a', 'audio/flac', 'audio/ogg',
        'audio/aac', 'audio/wma', 'video/mp4', 'video/avi', 'video/mov',
        'video/mkv', 'video/webm'
      ];
      
      // 文件类型验证
      if (!validTypes.includes(file.type)) {
        ElMessage.error('不支持的文件类型，请上传音频或视频文件');
        return false;
      }
      
      // 文件大小验证 (500MB)
      const maxSize = 500 * 1024 * 1024; // 500MB
      if (file.size > maxSize) {
        ElMessage.error('文件大小不能超过500MB');
        return false;
      }
      
      return true;
    };

    // 方法
    const createNewMeeting = () => {
      // 重置表单
      Object.keys(meetingForm).forEach(key => {
        if (key === 'participants') {
          meetingForm[key] = [];
        } else {
          meetingForm[key] = '';
        }
      });
      dialogVisible.value = true;
    };

    const saveMeeting = () => {
      // 简单验证
      if (!meetingForm.title) {
        ElMessage.error('请输入会议标题');
        return;
      }
      if (!meetingForm.date) {
        ElMessage.error('请选择会议日期');
        return;
      }

      // 模拟保存会议
      const newMeeting = {
        id: meetings.value.length + 1,
        title: meetingForm.title,
        date: meetingForm.date,
        status: '未开始',
      };
      meetings.value.push(newMeeting);
      dialogVisible.value = false;
      ElMessage.success('会议创建成功');
    };

    const viewMeetingDetail = (id) => {
      // 模拟查看会议详情
      ElMessage.info(`查看会议ID: ${id} 的详情`);
    };

    const startMeeting = (id) => {
      // 模拟开始会议
      const meeting = meetings.value.find(item => item.id === id);
      if (meeting) {
        meeting.status = '进行中';
        currentMeeting.value = {
          id: meeting.id,
          title: meeting.title,
          startTime: new Date().toLocaleString(),
          status: 'pending' // 添加状态字段
        };
        activeTab.value = 'ongoingMeeting';
        ElMessage.success('会议已开始');
      }
    };

    const startRecording = () => {
      // 模拟开始录音
      isRecording.value = true;
      ElMessage.success('录音已开始');
    };

    const stopRecording = () => {
      // 模拟停止录音
      isRecording.value = false;
      // 模拟添加一段转写内容
      transcription.value.push({
        speaker: '系统',
        content: '录音已停止，开始处理转写...',
      });
      ElMessage.success('录音已停止');
    };

    const handleFileSelect = (event) => {
      const file = event.target.files[0];
      if (file) {
        // 验证文件
        if (validateFile(file)) {
          selectedFile.value = file;
          uploadProgress.value = 0;
          // 清空文件输入，以便再次选择相同文件
          event.target.value = '';
        }
      }
    };

    const uploadAudio = async () => {
      // 触发文件选择对话框
      if (!selectedFile.value) {
        await nextTick();
        // 使用正确的方式获取文件输入元素
        const fileInput = document.querySelector('input[type="file"]');
        if (fileInput) {
          fileInput.click();
          return;
        } else {
          console.error('未找到文件输入元素');
          ElMessage.error('内部错误，请刷新页面重试');
        }
      }
      
      // 如果已经选择了文件，则执行上传
      if (selectedFile.value) {
        await processFileUpload();
      }
    };

    const processFileUpload = async () => {
      if (!selectedFile.value || !currentMeeting.value) {
        ElMessage.error('请先选择文件并确保有进行中的会议');
        return;
      }

      // 验证文件
      if (!validateFile(selectedFile.value)) {
        return;
      }

      // 获取会议标题
      const title = currentMeeting.value.title;
      const description = `上传的音频文件 - ${currentMeeting.value.title}`;

      isUploading.value = true;
      uploadProgress.value = 0;

      try {
        // 创建FormData对象
        const formData = new FormData();
        formData.append('file', selectedFile.value);
        formData.append('title', title);
        formData.append('description', description);
        // 移除不需要的meeting_id参数，因为当前API是上传文件并创建新会议
        // formData.append('meeting_id', currentMeeting.value.id);

        ElMessage.info('开始上传音频文件...');
        
        // 使用XMLHttpRequest上传文件以获取上传进度
        await uploadFileWithProgress(formData);
        
        // 上传成功后更新会议状态
        currentMeeting.value.status = 'processing';
        
        // 添加转写内容
        transcription.value.push({
          speaker: '系统',
          content: '音频上传成功，正在处理转写...',
        });
        
        ElMessage.success('文件上传成功，正在处理录音...');
        
        // 开始轮询获取转录状态
        startPollingForStatus();
        
        // 重置选择的文件
        selectedFile.value = null;
      } catch (error) {
        console.error('上传文件错误:', error);
        
        // 如果是模拟环境，给用户友好提示
        if (error.message.includes('Failed to fetch') || error.message === '模拟环境') {
          // 模拟上传成功
          currentMeeting.value.status = 'processing';
          transcription.value.push({
            speaker: '系统',
            content: '音频上传成功，正在处理转写...',
          });
          ElMessage.success('演示模式：音频上传成功（模拟），正在处理转写...');
          
          // 模拟转录完成
          setTimeout(() => {
            simulateTranscriptionComplete();
          }, 3000);
          
          selectedFile.value = null;
        } else {
          ElMessage.error('文件上传失败，请重试');
        }
      } finally {
        isUploading.value = false;
      }
    };

    // 使用XMLHttpRequest上传文件并获取进度
    const uploadFileWithProgress = (formData) => {
      return new Promise((resolve, reject) => {
        const xhr = new XMLHttpRequest();
        
        // 监听进度事件
        xhr.upload.addEventListener('progress', (event) => {
          if (event.lengthComputable) {
            const percentComplete = Math.round((event.loaded / event.total) * 100);
            uploadProgress.value = percentComplete;
          }
        });
        
        // 监听完成事件
        xhr.addEventListener('load', () => {
          if (xhr.status >= 200 && xhr.status < 300) {
            resolve(xhr.response);
          } else {
            reject(new Error(`上传失败: ${xhr.statusText}`));
          }
        });
        
        // 监听错误事件
        xhr.addEventListener('error', () => {
          reject(new Error('网络错误'));
        });
        
        // 监听超时事件
        xhr.addEventListener('timeout', () => {
          reject(new Error('上传超时'));
        });
        
        try {
          // 配置请求，使用正确的API端点
          xhr.open('POST', '/api/v1/meetings/upload', true);
          xhr.setRequestHeader('Authorization', `Bearer ${localStorage.getItem('access_token') || 'mock_token'}`);
          
          // 发送请求
          xhr.send(formData);
        } catch (error) {
          // 捕获浏览器安全策略导致的错误，进入模拟模式
          reject(new Error('模拟环境'));
        }
      });
    };

    // 开始轮询获取状态
    const startPollingForStatus = () => {
      // 清除之前的定时器
      if (pollTimer.value) {
        clearInterval(pollTimer.value);
      }
      
      // 设置新的轮询定时器
      pollTimer.value = setInterval(async () => {
        try {
          // 在真实环境中，这里会发送请求获取状态
          // 模拟状态检查
          if (Math.random() > 0.7) { // 模拟随机完成
            simulateTranscriptionComplete();
          }
        } catch (error) {
          console.error('获取状态失败:', error);
        }
      }, 5000); // 每5秒检查一次
    };

    // 模拟转录完成
    const simulateTranscriptionComplete = () => {
      if (pollTimer.value) {
        clearInterval(pollTimer.value);
        pollTimer.value = null;
      }
      
      currentMeeting.value.status = 'completed';
      
      // 添加模拟的转录结果
      const mockTranscriptions = [
        { speaker: '主持人', content: '大家好，欢迎参加今天的产品需求会议。' },
        { speaker: '产品经理', content: '我们今天主要讨论下一代产品的功能规划。' },
        { speaker: '技术负责人', content: '从技术角度看，我们需要考虑系统架构的扩展性。' },
        { speaker: 'UI设计师', content: '用户体验是我们需要重点关注的方向。' },
        { speaker: '项目经理', content: '我们需要制定一个详细的开发计划和时间表。' }
      ];
      
      transcription.value = [...transcription.value, ...mockTranscriptions];
      ElMessage.success('转写完成！');
    };

    const viewRecordDetail = (id) => {
      // 模拟查看记录详情
      ElMessage.info(`查看记录ID: ${id} 的详情`);
    };

    const generateSummary = (id) => {
      // 模拟生成总结
      ElMessage.info('开始生成会议总结...');
      setTimeout(() => {
        ElMessage.success('会议总结生成成功');
      }, 1000);
    };

    // 返回给模板使用的数据和方法
    return {
      activeTab,
      searchQuery,
      meetings,
      currentMeeting,
      isRecording,
      transcription,
      meetingRecords,
      dialogVisible,
      meetingForm,
      users,
      selectedFile,
      isUploading,
      uploadProgress,
      createNewMeeting,
      saveMeeting,
      viewMeetingDetail,
      startMeeting,
      startRecording,
      stopRecording,
      uploadAudio,
      handleFileSelect,
      viewRecordDetail,
      generateSummary,
    };
  },
};
</script>

<style scoped>
.meeting-assistant {
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.el-header {
  background-color: #ffffff;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 0 20px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 100%;
}

.avatar {
  margin-right: 10px;
}

.el-main {
  padding: 20px;
  overflow: auto;
  flex: 1;
}

.search-input {
  margin-bottom: 20px;
  width: 300px;
}

.ongoing-meeting {
  background-color: #f5f7fa;
  padding: 20px;
  border-radius: 8px;
}

.meeting-time {
  color: #606266;
  margin-bottom: 20px;
}

.meeting-controls {
  margin-bottom: 20px;
}

.meeting-controls .el-button {
  margin-right: 10px;
}

.selected-file {
  color: #606266;
  margin-bottom: 15px;
  font-size: 14px;
}

.upload-progress {
  color: #606266;
  margin-bottom: 15px;
  font-size: 14px;
}

.recording-status {
  display: flex;
  align-items: center;
  color: #f56c6c;
  margin-bottom: 20px;
}

.recording-icon {
  margin-right: 10px;
  animation: pulse 1.5s infinite;
}

@keyframes pulse {
  0% {
    opacity: 1;
  }
  50% {
    opacity: 0.5;
  }
  100% {
    opacity: 1;
  }
}

.transcription {
  background-color: #ffffff;
  padding: 15px;
  border-radius: 8px;
  max-height: 300px;
  overflow-y: auto;
}

.speaker {
  font-weight: bold;
  margin-right: 10px;
  color: #409eff;
}

.no-meeting {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 40px 0;
}

.empty-transcription {
  padding: 40px 0;
}
</style>